package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	"net/http"
)

func get_or_post(r *gin.Engine, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {
	routes := r.POST(relativePath, handlers...)
	routes = r.GET(relativePath, handlers...)
	return routes
}

var serveCmd = &cobra.Command{
	Use:   "serve",
	Short: "运行API微服务",
	Long: `例如：gmTool.exe serve
	`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Running the web api serve")

		// 加载SM2密钥
		loadHyPublicKey()
		loadPrivateKey()

		r := gin.Default()

		r.Any("/", func(c *gin.Context) {
			c.String(http.StatusOK, "国密加解密及签名验签微服务")
		})

		// sm2相关接口
		get_or_post(r, "/sm2/sign", r_sm2_sign)               //用自己的私钥签名
		get_or_post(r, "/sm2/verify", r_sm2_verify)           //用汇元的公钥检查汇元的签名
		get_or_post(r, "/sm2/self/verify", r_sm2_self_verify) //用自己的公钥检查自己的签名

		get_or_post(r, "/sm2/msg/verify", hy_message_verify)
		get_or_post(r, "/sm2/msg/sign", hy_message_sign)

		// rsa相关接口
		get_or_post(r, "/rsa/sign", rsa_sign)
		get_or_post(r, "/rsa/verify", rsa_verify)
		get_or_post(r, "/rsa/encrypt", rsa_encrypt)
		get_or_post(r, "/rsa/decrypt", rsa_decrypt)
		get_or_post(r, "/rsa/encrypt-sign", rsa_encrypt_sign)
		get_or_post(r, "/rsa/decrypt-verify", rsa_decrypt_verify)

		r.Run(gConfig.Listen) // listen and serve on 0.0.0.0:8080
	},
}

func init() {
	rootCmd.AddCommand(serveCmd)
}
